var angular = angular;
var console = console;

var loginApp    = angular.module('loginApp', ['angular-md5']);

loginApp.controller('loginController', ['$scope', '$http', 'md5', function ($scope, $http, md5) {
    'use strict';
    
    $scope.disabled = false;
    
    $scope.submitlogin = function () {
        if ((typeof ($scope.username) !== 'undefined') && (typeof ($scope.password) !== 'undefined')) {
            $scope.isError = false;
            $scope.disabled = true;
            $http({
                method: 'GET',
                url: 'api/login',
                params: {
                    username : $scope.username,
                    password : md5.createHash($scope.password || '')
                }
            }).success(function (data) {
                //console.log(data);
                if ((data.response === "OK") && (data.status_code == 200) && (data.message === 'Login success.')) {
                    $http({
                        method: 'GET',
                        url: 'putsession',
                        params: {
                            username : $scope.username,
                            role     : data.result.account.role
                        }
                    }).success(function (data) {
                        if ((data.response === "OK") && (data.status_code == 200) && (data.message === 'Adding username and role to sessions success.')) {
                            
                            window.location.href = '';
                        }
                    }).error(function (data) {
                        
                    }); // */
                } else {
                    $scope.disabled     = false;
                    $scope.isError      = true;
                    $scope.errormessage = data.message;
                }
            }).error(function (data) {
                console.log(data);
                $scope.disabled     = false;
                $scope.isError      = true;
                $scope.errormessage = 'Unknown error. Please try again';
            });
        }
    };
}]);
